package com.material.vtool.service.impl;

import com.github.pagehelper.PageHelper;
import com.material.vtool.entity.BTeamMaterialEntity;
import com.material.vtool.entity.combinedEntity.CombinedTeamMaterialEntity;
import com.material.vtool.entity.respEntity.ReturnCode;
import com.material.vtool.exception.ServiceException;
import com.material.vtool.mapper.TeamMaterialMapper;
import com.material.vtool.service.TeamMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeamMaterialServiceImpl implements TeamMaterialService {
    @Autowired
    private TeamMaterialMapper teamMaterialMapper;

    @Override
    public int save(BTeamMaterialEntity bTeamMaterialEntity) {
        return teamMaterialMapper.insertEntity(bTeamMaterialEntity);
    }

    @Override
    public List<CombinedTeamMaterialEntity> getTeamMaterialList(Integer pageNum, Integer pageSize, Integer teamId, Integer labelTypeId) {
        // 选择全部素材时，不再变更页码值
        if (labelTypeId.intValue() == -1) {
            pageNum = Integer.valueOf(1);
        }
        PageHelper.startPage(pageNum, pageSize);
        return teamMaterialMapper.getTeamMaterialList(teamId, labelTypeId);
    }

    @Override
    public int getTeamMaterialListTotal(Integer teamId, Integer labelTypeId) {
        Integer total = teamMaterialMapper.getTeamMaterialListTotal(teamId, labelTypeId);
        return total == null ? 0 : total.intValue();
    }

    @Override
    public int deleteTeamMaterialById(Integer id) {
        int affectedCount = teamMaterialMapper.updateTeamMaterialStatus(id, 0);
        if (affectedCount == 0) {
            throw new ServiceException("删除素材失败", ReturnCode.SERVER_ERROR);
        }
        return affectedCount;
    }

    @Override
    @Transactional
    public int updateTeamMaterialTopById(Integer id, Integer teamId) {
        // 先删除团队以前的置顶文章，再更新置顶文章
        teamMaterialMapper.deleteTeamMaterialTop(teamId);

        int affectedCount = teamMaterialMapper.updateTeamMaterialTopById(id);
        if (affectedCount == 0) {
            throw new ServiceException("素材置顶失败", ReturnCode.SERVER_ERROR);
        }
        return affectedCount;
    }

    @Override
    public BTeamMaterialEntity getTeamMemberMaterial(Integer userId, Integer materialId, Integer teamId) {
        return teamMaterialMapper.getTeamMemberMaterialCount(userId, teamId, materialId);
    }

    @Override
    public int updateTeamMemberMaterialActive(Integer userId, Integer materialId, Integer teamId) {
        Integer affectedCount = teamMaterialMapper.updateTeamMemberMaterialActive(userId, teamId, materialId);
        return affectedCount == null ? 0 : affectedCount.intValue();
    }
}
